package analyzer

import (
	"ddl_checker/pkg/database"
	"ddl_checker/pkg/types"
)

// PGQueryAnalyzer pg_query_go SQL分析器实现
type PGQueryAnalyzer struct {
	analyzer *database.GaussDBAnalyzer
}

// NewPGQueryAnalyzer 创建新的pg_query_go分析器
func NewPGQueryAnalyzer(enableDebug bool) *PGQueryAnalyzer {
	return &PGQueryAnalyzer{
		analyzer: database.NewGaussDBAnalyzer(enableDebug),
	}
}

// NewPostgreSQLAnalyzer 创建PostgreSQL分析器（别名）
func NewPostgreSQLAnalyzer(enableDebug bool) *PGQueryAnalyzer {
	return NewPGQueryAnalyzer(enableDebug)
}

// ParseBatch 解析多条SQL语句，拆分成多条
func (pga *PGQueryAnalyzer) ParseBatch(sql string, separator string) ([]*SQLStatement, error) {
	// 使用底层GaussDB分析器解析批量SQL
	statements, err := pga.analyzer.ParseBatchSQL(sql, separator)
	if err != nil {
		return nil, err
	}

	// 转换为接口定义的SQLStatement
	result := make([]*SQLStatement, len(statements))
	for i, stmt := range statements {
		result[i] = pga.convertStatement(stmt)
	}

	return result, nil
}

// ParseSingle 解析单条SQL语句
func (pga *PGQueryAnalyzer) ParseSingle(sql string) (*SQLStatement, error) {
	// 使用底层GaussDB分析器解析单条SQL
	stmt, err := pga.analyzer.ParseSQL(sql)
	if err != nil {
		return nil, err
	}

	return pga.convertStatement(stmt), nil
}

// ValidateSQL 验证SQL语句的语法正确性
func (pga *PGQueryAnalyzer) ValidateSQL(sql string) (bool, string) {
	return pga.analyzer.ValidateSQL(sql)
}

// SplitStatements 分割SQL语句，不进行语法解析
func (pga *PGQueryAnalyzer) SplitStatements(sql string, separator string) ([]string, error) {
	// 使用底层GaussDB分析器的ParseBatchSQL方法，它会自动分割语句
	statements, err := pga.analyzer.ParseBatchSQL(sql, separator)
	if err != nil {
		return nil, err
	}

	// 提取原始SQL
	result := make([]string, len(statements))
	for i, stmt := range statements {
		result[i] = stmt.OriginalSQL
	}

	return result, nil
}

// convertStatement 将底层SQLStatement转换为接口定义的SQLStatement
func (pga *PGQueryAnalyzer) convertStatement(stmt *database.SQLStatement) *SQLStatement {
	return &SQLStatement{
		OriginalSQL:   stmt.OriginalSQL,
		IsValid:       stmt.IsValid,
		StatementType: stmt.StatementType,
		Tables:        stmt.Tables,
		Columns:       stmt.Columns,
		Operations:    stmt.Operations,
		Error:         stmt.Error,
		Schema:        stmt.Schema,
		TableName:     stmt.TableName,
		ParserUsed:    types.ParserUsedPgQuery,
	}
}

// GetAnalysisResult 获取分析结果
func (pga *PGQueryAnalyzer) GetAnalysisResult(sql string, separator string) (*SQLAnalysisResult, error) {
	statements, err := pga.ParseBatch(sql, separator)
	if err != nil {
		return nil, err
	}

	result := &SQLAnalysisResult{
		Statements:        statements,
		TotalStatements:   len(statements),
		ValidStatements:   0,
		InvalidStatements: 0,
		Errors:            make([]string, 0),
	}

	for _, stmt := range statements {
		if stmt.IsValid {
			result.ValidStatements++
		} else {
			result.InvalidStatements++
			if stmt.Error != "" {
				result.Errors = append(result.Errors, stmt.Error)
			}
		}
	}

	return result, nil
}
